﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CrmEntity = Lmondeil.Crm.EF;

namespace Atlanchim.Crm.Mui.Pages.Actions
{
    public class PageEditActionModel : AbstractPageEditModel
    {
        public CrmEntity.Action Action { get; set; }

        public override void InnerLoad()
        {
            if (!string.IsNullOrEmpty(this.Fragment))
            {
                // Récupération des Ids
                int idAction = 0;
                int.TryParse(this.DicFragments["IdAction"], out idAction);

                int idContact = 0;
                if (this.DicFragments.ContainsKey("IdContact"))
                {
                    int.TryParse(this.DicFragments["IdContact"], out idContact);
                }

                // Chargement ou création de l'entité
                if (idAction > 0)
                {
                    this.Action = this._pageContext
                                        .Actions
                                        .Where(action => action.Id == idAction)
                                        .FirstOrDefault();
                }
                else
                {
                    this.Action = new CrmEntity.Action();
                    this.Action.Date = DateTime.Now.Date;
                    this.Action.Type = "Avance de phase";
                    this.Action.IdContact = idContact;
                    this._pageContext.Actions.Add(this.Action);
                }

                // Informations sur le contact
                if (idContact > 0)
                {
                    CrmEntity.Contact contact = this._pageContext
                                            .Contacts
                                            .Where(c => c.Id == idContact)
                                            .First();
                    this.Complement = string.Format("Contact =  {0} {1}", contact.Prenom, contact.Nom);
                }
            }
        }
    }
}
